<template>
  <div class="ai-interaction-container">
    <el-card>
      <div class="header">
        <el-input
          v-model="searchQuery"
          :placeholder="`搜索${searchType === 'id' ? 'ID' : searchType === 'nickname' ? '用户昵称' : '关键词'}`"
          style="width: 300px"
          @keyup.enter="handleSearch"
        >
          <el-select 
            v-model="searchType" 
            slot="prepend" 
            style="width: 100px"
          >
            <el-option label="关键词" value="keyword"></el-option>
            <el-option label="ID" value="id"></el-option>
            <el-option label="昵称" value="nickname"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
        <div class="operation-buttons">
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
            批量删除
          </el-button>
          <el-button type="primary" @click="handleAdd">
            新增对话
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="80">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="80">
          <template slot-scope="scope">
            {{ scope.row.id.toString().padStart(3, '0') }}
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="用户昵称" width="120"></el-table-column>
        <el-table-column prop="userQuery" label="用户提问" width="200"></el-table-column>
        <el-table-column prop="aiResponse" label="AI回复" width="300"></el-table-column>
        <el-table-column prop="emotionScore" label="情绪评分" width="120">
          <template slot-scope="scope">
            <el-tag :type="getEmotionTagType(scope.row.emotionScore)">
              {{ scope.row.emotionScore }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timestamp" label="时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="用户提问" prop="userQuery">
          <el-input v-model="form.userQuery"></el-input>
        </el-form-item>
        <el-form-item label="AI回复" prop="aiResponse">
          <el-input type="textarea" v-model="form.aiResponse" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="情绪评分" prop="emotionScore">
          <el-input-number 
            v-model="form.emotionScore" 
            :min="-10" 
            :max="10" 
            :step="1"
          ></el-input-number>
          <span style="margin-left: 10px; color: #666">
            (负值表示负面情绪，正值表示正面情绪)
          </span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 情绪预警监控面板 -->
    <el-dialog title="情绪预警监控" :visible.sync="monitorVisible" width="70%">
      <div class="monitor-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <div class="chart-title">情绪评分分布</div>
              <div id="emotionChart" style="height: 300px;"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="warning-list">
              <div class="warning-title">预警列表</div>
              <el-table :data="warningData" height="300" border>
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="userQuery" label="用户提问" width="200"></el-table-column>
                <el-table-column prop="emotionScore" label="情绪评分" width="120">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.emotionScore < -5 ? 'danger' : 'warning'">
                      {{ scope.row.emotionScore }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="timestamp" label="时间" width="180"></el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// Change the echarts import to use the full path
import echarts from 'echarts/dist/echarts.min.js';

export default {
  name: 'AIInteraction',
  data() {
    return {
      searchType: 'keyword', // 新增搜索类型
      searchQuery: '',
      tableData: [],
      selectedRows: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      monitorVisible: false,
      dialogTitle: '新增对话',
      form: {
        id: '',
        userQuery: '',
        aiResponse: '',
        emotionScore: 0,
        timestamp: ''
      },
      rules: {
        userQuery: [
          { required: true, message: '请输入用户提问内容', trigger: 'blur' }
        ],
        aiResponse: [
          { required: true, message: '请输入AI回复内容', trigger: 'blur' }
        ]
      },
      warningData: [],
      emotionChart: null
    };
  },
  mounted() {
    this.fetchData();
    this.$nextTick(() => {
      if (document.getElementById('emotionChart')) {
        this.initChart();
      }
    });
  },
  methods: {
    fetchData() {
      // 修改模拟数据，增加nickname字段
      this.tableData = [
        { id: 1, nickname: '用户A', userQuery: '我感觉很沮丧', aiResponse: '我理解你的感受，可以和我聊聊发生了什么吗？', emotionScore: -7, timestamp: '2023-05-10 14:30' },
        { id: 2, nickname: '用户B', userQuery: '今天天气真好', aiResponse: '是的，好天气能让人心情愉悦！', emotionScore: 8, timestamp: '2023-05-10 15:45' },
        { id: 3, nickname: '用户C', userQuery: '我睡不着怎么办', aiResponse: '建议尝试放松呼吸或听轻音乐', emotionScore: -3, timestamp: '2023-05-11 09:20' },
        { id: 4, nickname: '用户D', userQuery: '谢谢你的帮助', aiResponse: '不客气，随时为您服务！', emotionScore: 9, timestamp: '2023-05-11 10:15' },
        { id: 5, nickname: '用户E', userQuery: '我觉得生活没有意义', aiResponse: '您现在的感受很重要，建议寻求专业心理咨询', emotionScore: -9, timestamp: '2023-05-12 16:40' }
      ];
      this.total = this.tableData.length;
      this.warningData = this.tableData.filter(item => item.emotionScore < -5);
    },
    initChart() {
      this.emotionChart = echarts.init(document.getElementById('emotionChart'));
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '情绪分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.tableData.filter(item => item.emotionScore > 5).length, name: '积极' },
              { value: this.tableData.filter(item => item.emotionScore >= -5 && item.emotionScore <= 5).length, name: '中性' },
              { value: this.tableData.filter(item => item.emotionScore < -5).length, name: '消极' }
            ]
          }
        ]
      };
      this.emotionChart.setOption(option);
    },
    getEmotionTagType(score) {
      if (score > 5) return 'success';
      if (score < -5) return 'danger';
      return 'warning';
    },
    handleSearch() {
      // 实际项目中这里应该是API调用
      console.log('搜索:', this.searchQuery);
      this.currentPage = 1;
      this.fetchData();
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleBatchDelete() {
      this.$confirm('确定要删除选中的记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中这里应该是API调用
        const ids = this.selectedRows.map(item => item.id);
        this.tableData = this.tableData.filter(item => !ids.includes(item.id));
        this.total = this.tableData.length;
        this.$message.success('删除成功');
        this.selectedRows = [];
      });
    },
    handleAdd() {
      this.dialogTitle = '新增对话';
      this.form = {
        id: '',
        userQuery: '',
        aiResponse: '',
        emotionScore: 0,
        timestamp: new Date().toLocaleString()
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑对话';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确定要删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中这里应该是API调用
        this.tableData = this.tableData.filter(item => item.id !== row.id);
        this.total = this.tableData.length;
        this.$message.success('删除成功');
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            // 编辑
            const index = this.tableData.findIndex(item => item.id === this.form.id);
            this.tableData.splice(index, 1, this.form);
          } else {
            // 新增
            this.form.id = this.tableData.length + 1;
            this.tableData.unshift(this.form);
          }
          this.total = this.tableData.length;
          this.dialogVisible = false;
          this.$message.success('操作成功');
        }
      });
    },
    showMonitor() {
      this.monitorVisible = true;
      this.$nextTick(() => {
        this.initChart();
      });
    }
  }
};
</script>

<style scoped>
.ai-interaction-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.chart-container, .warning-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-title, .warning-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.monitor-container {
  padding: 10px;
}
</style>